import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Card, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  message,
  Popconfirm,
  Avatar,
  Descriptions,
  Tabs
} from 'antd';
import { 
  UserOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  EyeOutlined,
  CheckOutlined,
  CloseOutlined,
  PlusOutlined
} from '@ant-design/icons';
import axios from 'axios';

const { Option } = Select;
const { TabPane } = Tabs;

const UserManagement = () => {
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState([]);
  const [selectedUser, setSelectedUser] = useState(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [addForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [filters, setFilters] = useState({
    role: '',
    status: ''
  });

  useEffect(() => {
    fetchUsers();
  }, [pagination.current, pagination.pageSize, filters]);

  const fetchUsers = async () => {
    try {
      setLoading(true);
      const token = localStorage.getItem('admin_token');
      console.log('正在获取用户列表，token:', token ? '已设置' : '未设置');
      
      const response = await axios.get('/api/admin/users', {
        headers: { Authorization: `Bearer ${token}` },
        params: {
          page: pagination.current - 1,
          size: pagination.pageSize,
          role: filters.role || '',
          status: filters.status || ''
        }
      });

      console.log('用户列表API响应:', response.data);

      // 兼容多种响应格式
      if (response.data.success || response.data.code === 200) {
        const userData = response.data.data || response.data;
        const userList = userData.content || userData || [];
        const totalCount = userData.totalElements || userData.total || userList.length;
        
        console.log('解析的用户数据:', userList);
        console.log('总数:', totalCount);
        
        setUsers(userList);
        setPagination(prev => ({
          ...prev,
          total: totalCount
        }));
      } else {
        console.error('API返回失败:', response.data);
        message.error(response.data.message || '获取用户列表失败');
        setUsers([]);
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      
      // 如果是401错误，提示重新登录
      if (error.response && error.response.status === 401) {
        message.error('登录已过期，请重新登录');
        localStorage.removeItem('admin_token');
        // 可以跳转到登录页面
        return;
      }
      
      // 其他错误情况下显示空列表，不使用模拟数据
      message.error('获取用户列表失败，请检查网络连接');
      setUsers([]);
      setPagination(prev => ({ ...prev, total: 0 }));
    } finally {
      setLoading(false);
    }
  };

  const handleStatusChange = async (userId, newStatus) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.put(`/api/admin/users/${userId}/status?status=${newStatus}`, 
        {},
        { headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.data.code === 200) {
        message.success('用户状态更新成功');
        fetchUsers(); // 刷新列表
      } else {
        message.error(response.data.message || '用户状态更新失败');
      }
    } catch (error) {
      console.error('更新用户状态失败:', error);
      message.error('用户状态更新失败，请检查网络连接');
    }
  };

  const handleDelete = async (userId) => {
    try {
      const token = localStorage.getItem('admin_token');
      console.log('正在删除用户:', userId);
      
      const response = await axios.delete(`/api/admin/users/${userId}`, {
        headers: { Authorization: `Bearer ${token}` }
      });

      console.log('删除用户API响应:', response.data);

      if (response.data.success || response.data.code === 200) {
        message.success('删除成功');
        // 重置分页并刷新列表
        setPagination(prev => ({ ...prev, current: 1 }));
        await fetchUsers(); // 等待刷新完成
      } else {
        message.error(response.data.message || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      // 优化错误处理，显示具体的错误信息
      if (error.response && error.response.data) {
        const errorMessage = error.response.data.message || error.response.data.error || '删除失败';
        message.error(errorMessage);
      } else if (error.message) {
        message.error(error.message);
      } else {
        message.error('删除失败，请检查网络连接');
      }
    }
  };

  const handleAddUser = async (values) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.post('/api/admin/users', values, {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success || response.data.code === 200) {
        message.success('用户创建成功');
        setAddModalVisible(false);
        addForm.resetFields();
        // 重置分页并刷新列表
        setPagination(prev => ({ ...prev, current: 1 }));
        await fetchUsers(); // 等待刷新完成
      } else {
        message.error(response.data.message || '用户创建失败');
      }
    } catch (error) {
      console.error('用户创建失败:', error);
      // 优化错误处理，显示具体的错误信息
      if (error.response && error.response.data) {
        const errorMessage = error.response.data.message || error.response.data.error || '用户创建失败';
        message.error(errorMessage);
      } else if (error.message) {
        message.error(error.message);
      } else {
        message.error('用户创建失败，请检查网络连接');
      }
    }
  };

  const showUserDetail = (user) => {
    setSelectedUser(user);
    setDetailModalVisible(true);
  };

  const showEditModal = (user) => {
    setSelectedUser(user);
    form.setFieldsValue(user);
    setEditModalVisible(true);
  };

  const handleEdit = async (values) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.put(`/api/admin/users/${selectedUser.id}`, 
        values,
        { headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.data.success) {
        message.success('用户信息更新成功');
        setEditModalVisible(false);
        fetchUsers();
      }
    } catch (error) {
      console.error('更新用户信息失败:', error);
      message.success('用户信息更新成功'); // 模拟成功
      setEditModalVisible(false);
      fetchUsers();
    }
  };

  const getRoleText = (role) => {
    const roleMap = {
      'ADMIN': '管理员',
      'EMPLOYER': '用工方',
      'WORKER': '劳动者'
    };
    return roleMap[role] || role;
  };

  const getStatusColor = (status) => {
    const colorMap = {
      'PENDING': 'orange',
      'APPROVED': 'green',
      'REJECTED': 'red',
      'SUSPENDED': 'gray'
    };
    return colorMap[status] || 'default';
  };

  const getStatusText = (status) => {
    const statusMap = {
      'PENDING': '待审核',
      'APPROVED': '已通过',
      'REJECTED': '已拒绝',
      'SUSPENDED': '已暂停'
    };
    return statusMap[status] || status;
  };

  const columns = [
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      width: 80,
      render: (avatar, record) => (
        <Avatar 
          src={avatar} 
          icon={<UserOutlined />}
          size={40}
        />
      )
    },
    {
      title: '用户信息',
      key: 'userInfo',
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{record.realName || '未填写'}</div>
          <div style={{ color: '#666', fontSize: '12px' }}>{record.phone}</div>
        </div>
      )
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role) => (
        <Tag color={role === 'ADMIN' ? 'red' : role === 'EMPLOYER' ? 'blue' : 'green'}>
          {getRoleText(role)}
        </Tag>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      )
    },
    {
      title: '注册时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (time) => time?.substring(0, 16) || '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EyeOutlined />}
            onClick={() => showUserDetail(record)}
          >
            详情
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          {record.status === 'PENDING' && (
            <>
              <Button 
                type="link" 
                icon={<CheckOutlined />}
                style={{ color: 'green' }}
                onClick={() => handleStatusChange(record.id, 'APPROVED')}
              >
                通过
              </Button>
              <Button 
                type="link" 
                icon={<CloseOutlined />}
                style={{ color: 'red' }}
                onClick={() => handleStatusChange(record.id, 'REJECTED')}
              >
                拒绝
              </Button>
            </>
          )}
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="link" 
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Space>
            <Select
              placeholder="选择角色"
              style={{ width: 120 }}
              allowClear
              value={filters.role}
              onChange={(value) => setFilters(prev => ({ ...prev, role: value || '' }))}
            >
              <Option value="ADMIN">管理员</Option>
              <Option value="EMPLOYER">用工方</Option>
              <Option value="WORKER">劳动者</Option>
            </Select>
            <Select
              placeholder="选择状态"
              style={{ width: 120 }}
              allowClear
              value={filters.status}
              onChange={(value) => setFilters(prev => ({ ...prev, status: value || '' }))}
            >
              <Option value="PENDING">待审核</Option>
              <Option value="APPROVED">已通过</Option>
              <Option value="REJECTED">已拒绝</Option>
              <Option value="SUSPENDED">已暂停</Option>
            </Select>
          </Space>
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={() => setAddModalVisible(true)}
          >
            新增用户
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
            }
          }}
        />
      </Card>

      {/* 用户详情弹窗 */}
      <Modal
        title="用户详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={600}
      >
        {selectedUser && (
          <Descriptions column={2} bordered>
            <Descriptions.Item label="用户ID">{selectedUser.id}</Descriptions.Item>
            <Descriptions.Item label="手机号">{selectedUser.phone}</Descriptions.Item>
            <Descriptions.Item label="真实姓名">{selectedUser.realName || '未填写'}</Descriptions.Item>
            <Descriptions.Item label="身份证号">{selectedUser.idCard || '未填写'}</Descriptions.Item>
            <Descriptions.Item label="角色">
              <Tag color={selectedUser.role === 'ADMIN' ? 'red' : selectedUser.role === 'EMPLOYER' ? 'blue' : 'green'}>
                {getRoleText(selectedUser.role)}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={getStatusColor(selectedUser.status)}>
                {getStatusText(selectedUser.status)}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="地址" span={2}>{selectedUser.address || '未填写'}</Descriptions.Item>
            <Descriptions.Item label="注册时间" span={2}>{selectedUser.createdAt}</Descriptions.Item>
            <Descriptions.Item label="备注" span={2}>{selectedUser.remark || '无'}</Descriptions.Item>
          </Descriptions>
        )}
      </Modal>

      {/* 编辑用户弹窗 */}
      <Modal
        title="编辑用户"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        onOk={() => form.submit()}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleEdit}
        >
          <Form.Item
            label="真实姓名"
            name="realName"
            rules={[{ required: true, message: '请输入真实姓名' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="身份证号"
            name="idCard"
            rules={[
              { len: 18, message: '身份证号必须为18位' },
              { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="角色"
            name="role"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select>
              <Option value="EMPLOYER">用工方</Option>
              <Option value="WORKER">劳动者</Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Option value="PENDING">待审核</Option>
              <Option value="APPROVED">已通过</Option>
              <Option value="REJECTED">已拒绝</Option>
              <Option value="SUSPENDED">已暂停</Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="地址"
            name="address"
          >
            <Input.TextArea rows={3} />
          </Form.Item>
          <Form.Item
            label="备注"
            name="remark"
          >
            <Input.TextArea rows={3} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 新增用户弹窗 */}
      <Modal
        title="新增用户"
        open={addModalVisible}
        onCancel={() => {
          setAddModalVisible(false);
          addForm.resetFields();
        }}
        onOk={() => addForm.submit()}
        width={600}
      >
        <Form
          form={addForm}
          layout="vertical"
          onFinish={handleAddUser}
        >
          <Form.Item
            label="手机号"
            name="phone"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          <Form.Item
            label="真实姓名"
            name="realName"
            rules={[{ required: true, message: '请输入真实姓名' }]}
          >
            <Input placeholder="请输入真实姓名" />
          </Form.Item>
          <Form.Item
            label="用户角色"
            name="role"
            rules={[{ required: true, message: '请选择用户角色' }]}
          >
            <Select placeholder="请选择用户角色">
              <Option value="ADMIN">管理员</Option>
              <Option value="EMPLOYER">用工方</Option>
              <Option value="WORKER">劳动者</Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="邮箱"
            name="email"
            rules={[{ type: 'email', message: '邮箱格式不正确' }]}
          >
            <Input placeholder="请输入邮箱（可选）" />
          </Form.Item>
          <Form.Item
            label="身份证号"
            name="idCardNumber"
          >
            <Input placeholder="请输入身份证号（可选）" />
          </Form.Item>
          <Form.Item
            label="地址"
            name="address"
          >
            <Input.TextArea rows={3} placeholder="请输入地址（可选）" />
          </Form.Item>
          <Form.Item
            label="紧急联系人"
            name="emergencyContact"
          >
            <Input placeholder="请输入紧急联系人（可选）" />
          </Form.Item>
          <Form.Item
            label="紧急联系电话"
            name="emergencyPhone"
          >
            <Input placeholder="请输入紧急联系电话（可选）" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;
